<?php
namespace app\admin\controller;
use app\admin\model\CategroySpecification;
use \app\admin\controller\BaseController;
use \app\admin\model\Categroy;
use app\foundation\Upload;
use think\Loader;

class Category extends BaseController
{
	public function index(Categroy $categroy)
	{
		$this->isLogin();
            $list = $categroy->where('pid = 0 ')->paginate(2);
            foreach ($list as $key => $values) {
                $min = $categroy->where('pid = '.$values['id'] )->select()->toArray();
                foreach ($min as $k => $value) {
                    $three = $categroy->where('pid = '. $value['id'])->select()->toArray();
                    $min[$k]['three'] = $three;
                    $list[$key]['min'] = $min;
                }
            }
        return view('category/index', compact('list'));
	}
	public function select(Categroy $categroy)
	{
		$this->isLogin();
        $grade = input('grade');
        $name = input('categroy_name');
	    if(strlen($grade) == '1' && strlen($name) == '0'){
            if($grade == '0'){
                $list = $categroy->where('pid',0)->paginate(10,false,['query' => input('get.')]);
            }elseif($grade == '1'){
                $list = $categroy->where('grade',2)->paginate(10,false,['query' => input('get.')]);
            }elseif($grade == '2'){
                $list = $categroy->where('grade',3)->paginate(10,false,['query' => input('get.')]);
            }
        }elseif(strlen($grade) == '1'  && strlen($name) != '0' ){
            if($grade == '0'){
                $list = $categroy->where('pid',0)->where('categroy_name','like',['%'.$name,$name.'%'],'OR')->paginate(10,false,['query' => input('get.')]);
            }elseif($grade == '1'){
                $list = $categroy->where('grade',2)->where('categroy_name','like',['%'.$name,$name.'%'],'OR')->paginate(10,false,['query' => input('get.')]);
            }elseif($grade == '2'){
                $list = $categroy->where('grade',3)->where('categroy_name','like',['%'.$name,$name.'%'],'OR')->paginate(10,false,['query' => input('get.')]);
            }
        }elseif(strlen($grade) == '0' && strlen($name) != '0'){
            $list = $categroy->where('categroy_name','like',['%'.$name,$name.'%'],'OR')->paginate(10,false,['query' => input('get.')]);
        }
        if(!$list) $this->error('暂无搜索数据');
        return view('category/index', compact('list'));
	}
	public function insert()
	{
		$this->isLogin();
		return view('', compact(''));
	}
	/**
	 * 获取分类列表
	 */
	public function getCategroy(Categroy $categroy)
	{
		$this->isLogin();
		$type = input('post.type');
		$categroy_id = input('post.categroy');
		if(!$type) {
			$result = $categroy->where(['pid' => 0, 'is_use' => 0, 'grade' => 1])->select()->toArray();
		} else if ($type == '1') {
			$result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 2])->select()->toArray();
		} elseif ($type == '2'){
			$result = $categroy->where(['pid' => $categroy_id, 'is_use' => 0, 'grade' => 3])->select()->toArray();
        }
		return json_encode($result,  JSON_UNESCAPED_UNICODE);
	}
	/**
	 * 添加分类
	 * @param  Categroy $categroy [description]
	 * @return [type]             [description]
	 */
	public function insertCategroy(Categroy $categroys)
	{
		$this->isLogin();
		$type = input('post.type');
		$categroy = input('post.categroy');
		$categroy_name = input('post.categroy_name');
		$data['categroy_name'] = $categroy_name;
		$data['is_use'] = 0;
		$data['create_time'] = time();
		if($type == '1') {
			$data['pid'] = 0;
			$data['grade'] = 1;
		} else if($type == '2') {
			$data['pid'] = $categroy;
			$data['grade'] = 2;
		} else {
			$data['pid'] = $categroy;
			$data['grade'] = 3;
			$files = request()->file('img');
			$info = $files->move('upload');
			if ($info) {
				$data['image'] = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
			}
		}
        $res = $categroys->where('categroy_name',$categroy_name)->count();
		if($res >= 1){
		    return json(['code'=>300,'msg'=>'该分类名已存在']);
        }else{
            $result = $categroys->save($data);
            if($result) {
                $lastId = $categroys->getLastInsID();
                return json(['id'=>$lastId]);
            }
            return json(['code'=>100,'msg'=>'分类添加失败']);
        }
    }
	/**
	 * 添加三级分类
	 * @return [type] [description]
	 */
//	public function insertCategroyThree(Categroy $categroys)
//	{
//		$this->isLogin();
//		$data['categroy_name'] = input('post.categroy_name');
//		$data['is_use'] = 0;
//		$data['create_time'] = time();
//		$data['pid'] = input('post.categroy');;
//		$data['grade'] = 3;
//		$files = request()->file('img');
//		$info = $files->move('upload');
//		if ($info) {
//			$data['image'] = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
//		}
//        $res = $categroys->where('categroy_name', input('categroy_name'))->count();
//		if($res >=1){
//		    return $this->error('该分类已存在');
//        }
//		$result = $categroys->save($data);
//		if($result) {
//			$this->redirect($_SERVER["HTTP_REFERER"]);
//		}
//		return $this->error('添加失败');
//	}
	/**
	 * 修改分类
	 * @param  [type] $categroy      [description]
	 * @param  [type] $categroy_name [description]
	 * @return [type]                [description]
	 */
	public function update(Categroy $categroy)
	{
		$this->isLogin();
		$categroy_id = input('post.id');
		$post['categroy_name'] = input('post.categroy_name');
		if($_FILES) {
			$files = request()->file('img');
			if(!$files) {
				$this->error('轮播图不能为空');
			}
			$info = $files->move('upload');
			if ($info) {
				$post['image'] = '\\upload\\' . date('Ymd').'\\'.$info->getFilename();
			} else {
				$this->error('轮播图不能为空');
			}
		}
		$result = $categroy->where(['id' => $categroy_id])->update($post);
		if($result) {
			$this->redirect($_SERVER["HTTP_REFERER"]);
		}
		return $this->error('修改失败');
	}
	/**
	 * 删除分类
	 * @param  Categroy $categroy [description]
	 * @return [type]             [description]
	 */
    public function delete(Categroy $categroy)
    {
        $this->isLogin();
        $type = input('type');
        $id = input('id');
        if($type == '1') {
            $one = $categroy->where(['pid' => $id, 'is_use' => 0])->count();
            if($one) {
                $this->error('请先删除该分类下的二级类及三级类');
            }
            $result = $categroy->where(['id' => $id])->update(['is_use' => 1]);
        }elseif($type == '2') {
            $one = $categroy->where(['pid' => $id, 'is_use' => 0])->count();
            if($one) {
                $this->error('请先删除该分类下的三级类');
            }
            $result = $categroy->where(['id' => $id])->update(['is_use' => 1]);
        }elseif($type == '3') {
            $result = $categroy->where('id', $id)->update(['is_use' => 1]);
        }
        if($result){
            return $this->redirect($_SERVER["HTTP_REFERER"]);
        }
        return $this->error('操作失败，请联系管理员');
    }
	public function recovery(Categroy $categroy)
	{
        $this->isLogin();
        $type = input('type');
        $pid = input('pid');
        $id = input('id');
        if($type == '3') {
            $one = $categroy->where('id', $pid)->where('is_use',1)->count();
            if($one){
                return $this->error('请先恢复该分类的一级类及二级类');
            }
            $result = $categroy->where(['id' => $id])->update(['is_use' => 0]);
        }elseif($type == '2') {
            $one = $categroy->where('id', $pid)->where('is_use',1)->count();
            if($one){
                return $this->error('请先恢复该分类的一级类');
            }
            $result = $categroy->where(['id' => $id])->update(['is_use' => 0]);
        }elseif($type == '1') {
            $result = $categroy->where(['id' => $id])->update(['is_use' => 0]);
        }
        if($result){
            return $this->redirect($_SERVER["HTTP_REFERER"]);
        }
        return $this->error('操作失败，请联系管理员');
	}
    /**
     * 添加分类规格展示页面
     * @return \think\response\View
     */
	public function specAdd(){
		$this->isLogin();
	    return view('category/insertType');
    }
    //分类规格保存页面
    public function specSave(CategroySpecification $spec)
    {
        $this->isLogin();
        if(request()->isPost()){
            $result = $spec->addSpec(input('post.'));
            if($result['valid'] == 0){
                return $this->error($result['message']);
            }elseif($result['valid'] == 1){
                return $this->success($result['message']);
            }elseif($result['valid'] == 2){
                return $this->error($result['message']);
            }else{
                return $this->error($result['message']);
            }
        }
    }
    /**
     * 分类规格编辑页面
     * @return \think\response\View
     */
    public function specUpdateShow(CategroySpecification $spec)
    {
    	$this->isLogin();
        if(request()->isPost()){
            $result = $spec->updateSpec(input('post.'));
            if($result['valid'] == 0){
                return json(['code'=>100,'msg'=>$result['message']]);
            }elseif($result['valid'] == 1){
                return json(['code'=>200,'msg'=>$result['message']]);
            }else{
                return json(['code'=>300,'msg'=>$result['message']]);
            }
        }
        return view('category/updateType');
    }
    //规格修改
    public function specUpdated(CategroySpecification $spec)
    {
    	$this->isLogin();
        if(request()->isPost()){
            $res =  $spec->where('categroy_id',input('categroy_id'))->where('spec_staff',input('spec_staff'))->find();
        }
        return json($res);
    }
    public function aa(Categroy $categroy)
    {
        $cates = $categroy->select();
        $result = $this->tree($cates,$pid = 0,$count = 1);
        return view('category/aa',compact('result'));
    }
    public function tree($data,$pid=0,$level=1)
    {
        static $treeArr = array();
        foreach ($data as $v)
        {
            if ($v['pid'] == $pid)
            {
                $v['level'] = $level;
                $treeArr[] = $v;
                $this->tree($data, $v['id'], $level + 1);
            }
        }
        return $treeArr;
    }
}
